# 失物招领系统
from django import forms
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.forms.models import model_to_dict
from web.models import LostAndFound, Users, LostAndFoundImage
from web.apis import tools
from django.db.models import Q
import uuid
import os

# 失物招领表单
class LostAndFoundForm(forms.ModelForm):
    class Meta:
        model = LostAndFound
        fields = ['lost_and_found_name', 'lost_and_found_description', 'lost_and_found_status', 
                 'lost_and_found_claimer_name', 'lost_and_found_claimer_contact', 
                 'lost_and_found_creator', 'lost_and_found_location']
        exclude = ['lost_and_found_id', 'create_time', 'update_time']

    def clean_lost_and_found_name(self):
        lost_and_found_name = self.cleaned_data.get('lost_and_found_name')
        if not lost_and_found_name:
            raise forms.ValidationError("物品名称不能为空")
        if len(lost_and_found_name) > 100:
            raise forms.ValidationError("物品名称不能超过100个字符")
        return lost_and_found_name

    def clean_lost_and_found_status(self):
        lost_and_found_status = self.cleaned_data.get('lost_and_found_status')
        if lost_and_found_status not in [1, 2, 3]:  # 1: 待认领, 2: 已认领, 3: 已失效
            raise forms.ValidationError("物品状态格式不正确")
        return lost_and_found_status

    def clean_lost_and_found_location(self):
        lost_and_found_location = self.cleaned_data.get('lost_and_found_location')
        if not lost_and_found_location:
            raise forms.ValidationError("物品位置不能为空")
        if len(lost_and_found_location) > 100:
            raise forms.ValidationError("物品位置不能超过100个字符")
        return lost_and_found_location

    def clean_lost_and_found_description(self):
        lost_and_found_description = self.cleaned_data.get('lost_and_found_description')
        if not lost_and_found_description:
            raise forms.ValidationError("物品描述不能为空")
        if len(lost_and_found_description) > 500:
            raise forms.ValidationError("物品描述不能超过500个字符")
        return lost_and_found_description

    def clean(self):
        cleaned_data = super().clean()
        status = cleaned_data.get('lost_and_found_status')
        claimer_name = cleaned_data.get('lost_and_found_claimer_name')
        claimer_contact = cleaned_data.get('lost_and_found_claimer_contact')
        if status == 2:
            if not claimer_name:
                self.add_error('lost_and_found_claimer_name', '认领者姓名为必填项（已认领时）')
            if not claimer_contact:
                self.add_error('lost_and_found_claimer_contact', '认领者联系方式为必填项（已认领时）')
        return cleaned_data

# 创建失物招领记录
@csrf_exempt
def create_lost_and_found(request):
    if request.method == 'POST':
        form = LostAndFoundForm(request.POST)
        if form.is_valid():
            try:
                # 创建失物招领记录
                item = form.save(commit=False)
                item.lost_and_found_id = str(uuid.uuid4())  # 手动设置 lost_and_found_id
                item.save()
                
                item_dict = model_to_dict(item)
                item_dict['create_time'] = item.create_time.strftime('%Y-%m-%d %H:%M:%S')
                item_dict['update_time'] = item.update_time.strftime('%Y-%m-%d %H:%M:%S')
                
                # 获取创建者信息
                if item.lost_and_found_creator:
                    user = Users.objects.filter(id=item.lost_and_found_creator.id).first()
                    if user:
                        item_dict['user'] = model_to_dict(user)
                        del item_dict['user']['password']
                        item_dict['user']['create_time'] = user.create_time.strftime('%Y-%m-%d %H:%M:%S')
                        item_dict['user']['update_time'] = user.update_time.strftime('%Y-%m-%d %H:%M:%S')
                        item_dict['user']['avatar'] = user.avatar.url if user.avatar else None
                
                # 获取物品图片
                images = LostAndFoundImage.objects.filter(lost_and_found=item)
                image_list = []
                for image in images:
                    image_dict = {
                        'id': image.id,
                        'image': image.image.url if image.image else None,
                        'create_time': image.create_time.strftime('%Y-%m-%d %H:%M:%S'),
                        'update_time': image.update_time.strftime('%Y-%m-%d %H:%M:%S')
                    }
                    image_list.append(image_dict)
                item_dict['images'] = image_list
                
                return JsonResponse(tools.ReturnData(code=200, msg='创建失物招领记录成功', data=item_dict))
            except Exception as e:
                return JsonResponse(tools.ReturnData(code=400, msg=f'创建失物招领记录失败: {str(e)}'))
        else:
            error_msg = tools.get_first_error(form)
            return JsonResponse(tools.ReturnData(code=400, msg=f' {error_msg}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用POST方法'))

# 获取失物招领记录列表
@csrf_exempt
def get_lost_and_found_list(request):
    if request.method == 'GET':
        try:
            items = LostAndFound.objects.all().order_by('-create_time')
            item_list = []
            for item in items:
                item_dict = model_to_dict(item)
                item_dict['create_time'] = item.create_time.strftime('%Y-%m-%d %H:%M:%S')
                item_dict['update_time'] = item.update_time.strftime('%Y-%m-%d %H:%M:%S')
                
                # 获取创建者信息
                if item.lost_and_found_creator:
                    user = Users.objects.filter(id=item.lost_and_found_creator.id).first()
                    if user:
                        item_dict['user'] = model_to_dict(user)
                        del item_dict['user']['password']
                        item_dict['user']['create_time'] = user.create_time.strftime('%Y-%m-%d %H:%M:%S')
                        item_dict['user']['update_time'] = user.update_time.strftime('%Y-%m-%d %H:%M:%S')
                        item_dict['user']['avatar'] = user.avatar.url if user.avatar else None
                
                # 获取物品图片
                images = LostAndFoundImage.objects.filter(lost_and_found=item)
                image_list = []
                for image in images:
                    image_dict = {
                        'id': image.id,
                        'image': image.image.url if image.image else None,
                        'create_time': image.create_time.strftime('%Y-%m-%d %H:%M:%S'),
                        'update_time': image.update_time.strftime('%Y-%m-%d %H:%M:%S')
                    }
                    image_list.append(image_dict)
                item_dict['images'] = image_list
                
                item_list.append(item_dict)
            return JsonResponse(tools.ReturnData(code=200, msg='获取失物招领记录列表成功', data=item_list))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'获取失物招领记录列表失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用GET方法'))

# 获取单个失物招领记录
@csrf_exempt
def get_lost_and_found(request, lost_and_found_id):
    if request.method == 'GET':
        try:
            item = LostAndFound.objects.filter(lost_and_found_id=lost_and_found_id).first()
            if not item:
                return JsonResponse(tools.ReturnData(code=400, msg='失物招领记录不存在'))
            
            item_dict = model_to_dict(item)
            item_dict['create_time'] = item.create_time.strftime('%Y-%m-%d %H:%M:%S')
            item_dict['update_time'] = item.update_time.strftime('%Y-%m-%d %H:%M:%S')
            
            # 获取创建者信息
            if item.lost_and_found_creator:
                user = Users.objects.filter(id=item.lost_and_found_creator.id).first()
                if user:
                    item_dict['user'] = model_to_dict(user)
                    del item_dict['user']['password']
                    item_dict['user']['create_time'] = user.create_time.strftime('%Y-%m-%d %H:%M:%S')
                    item_dict['user']['update_time'] = user.update_time.strftime('%Y-%m-%d %H:%M:%S')
                    item_dict['user']['avatar'] = user.avatar.url if user.avatar else None
            
            # 获取物品图片
            images = LostAndFoundImage.objects.filter(lost_and_found=item)
            image_list = []
            for image in images:
                image_dict = {
                    'id': image.id,
                    'image': image.image.url if image.image else None,
                    'create_time': image.create_time.strftime('%Y-%m-%d %H:%M:%S'),
                    'update_time': image.update_time.strftime('%Y-%m-%d %H:%M:%S')
                }
                image_list.append(image_dict)
            item_dict['images'] = image_list
            
            return JsonResponse(tools.ReturnData(code=200, msg='获取失物招领记录成功', data=item_dict))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'获取失物招领记录失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用GET方法'))

# 更新失物招领记录
@csrf_exempt
def update_lost_and_found(request, lost_and_found_id):
    if request.method == 'POST':
        try:
            item = LostAndFound.objects.filter(lost_and_found_id=lost_and_found_id).first()
            if not item:
                return JsonResponse(tools.ReturnData(code=400, msg='失物招领记录不存在'))
            
            form = LostAndFoundForm(request.POST, instance=item)
            if form.is_valid():
                # 更新失物招领记录
                form.save()
                
                item_dict = model_to_dict(form.instance)
                item_dict['create_time'] = form.instance.create_time.strftime('%Y-%m-%d %H:%M:%S')
                item_dict['update_time'] = form.instance.update_time.strftime('%Y-%m-%d %H:%M:%S')
                
                # 获取创建者信息
                if form.instance.lost_and_found_creator:
                    user = Users.objects.filter(id=form.instance.lost_and_found_creator.id).first()
                    if user:
                        item_dict['user'] = model_to_dict(user)
                        del item_dict['user']['password']
                        item_dict['user']['create_time'] = user.create_time.strftime('%Y-%m-%d %H:%M:%S')
                        item_dict['user']['update_time'] = user.update_time.strftime('%Y-%m-%d %H:%M:%S')
                        item_dict['user']['avatar'] = user.avatar.url if user.avatar else None
                
                # 获取物品图片
                images = LostAndFoundImage.objects.filter(lost_and_found=form.instance)
                image_list = []
                for image in images:
                    image_dict = {
                        'id': image.id,
                        'image': image.image.url if image.image else None,
                        'create_time': image.create_time.strftime('%Y-%m-%d %H:%M:%S'),
                        'update_time': image.update_time.strftime('%Y-%m-%d %H:%M:%S')
                    }
                    image_list.append(image_dict)
                item_dict['images'] = image_list
                
                return JsonResponse(tools.ReturnData(code=200, msg='更新失物招领记录成功', data=item_dict))
            else:
                error_msg = tools.get_first_error(form)
                return JsonResponse(tools.ReturnData(code=400, msg=f' {error_msg}'))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'更新失物招领记录失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用POST方法'))

# 删除失物招领记录
@csrf_exempt
def delete_lost_and_found(request, lost_and_found_id):
    if request.method == 'DELETE':
        try:
            item = LostAndFound.objects.filter(lost_and_found_id=lost_and_found_id).first()
            if not item:
                return JsonResponse(tools.ReturnData(code=400, msg='失物招领记录不存在'))
            
            # 删除失物招领记录
            item.delete()
            return JsonResponse(tools.ReturnData(code=200, msg='删除失物招领记录成功'))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'删除失物招领记录失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用DELETE方法'))

# 搜索失物招领记录
@csrf_exempt
def search_lost_and_found(request):
    """
    支持的搜索字段:
    物品名称
    物品位置
    认领者姓名
    认领者联系方式
    创建者
    物品描述
    物品ID
    """
    if request.method == 'GET':
        keyword = request.GET.get('keyword', '').strip()
        try:
            query = Q()
            if keyword:
                # 搜索物品名称
                query |= Q(lost_and_found_name__icontains=keyword)
                # 搜索物品位置
                query |= Q(lost_and_found_location__icontains=keyword)
                # 搜索认领者姓名
                query |= Q(lost_and_found_claimer_name__icontains=keyword)
                # 搜索认领者联系方式
                query |= Q(lost_and_found_claimer_contact__icontains=keyword)
                # 搜索创建者
                query |= Q(lost_and_found_creator__username__icontains=keyword)
                # 搜索物品描述
                query |= Q(lost_and_found_description__icontains=keyword)
                # 搜索物品ID
                query |= Q(lost_and_found_id__icontains=keyword)
            
            items = LostAndFound.objects.filter(query).order_by('-create_time')
            item_list = []
            for item in items:
                item_dict = model_to_dict(item)
                item_dict['create_time'] = item.create_time.strftime('%Y-%m-%d %H:%M:%S')
                item_dict['update_time'] = item.update_time.strftime('%Y-%m-%d %H:%M:%S')
                
                # 获取创建者信息
                if item.lost_and_found_creator:
                    user = Users.objects.filter(id=item.lost_and_found_creator.id).first()
                    if user:
                        item_dict['user'] = model_to_dict(user)
                        del item_dict['user']['password']
                        item_dict['user']['create_time'] = user.create_time.strftime('%Y-%m-%d %H:%M:%S')
                        item_dict['user']['update_time'] = user.update_time.strftime('%Y-%m-%d %H:%M:%S')
                        item_dict['user']['avatar'] = user.avatar.url if user.avatar else None
                
                # 获取物品图片
                images = LostAndFoundImage.objects.filter(lost_and_found=item)
                image_list = []
                for image in images:
                    image_dict = {
                        'id': image.id,
                        'image': image.image.url if image.image else None,
                        'create_time': image.create_time.strftime('%Y-%m-%d %H:%M:%S'),
                        'update_time': image.update_time.strftime('%Y-%m-%d %H:%M:%S')
                    }
                    image_list.append(image_dict)
                item_dict['images'] = image_list
                
                item_list.append(item_dict)
            return JsonResponse(tools.ReturnData(code=200, msg='搜索失物招领记录成功', data=item_list))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'搜索失物招领记录失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用GET方法'))

# 上传失物招领图片
@csrf_exempt
def upload_lost_and_found_image(request, lost_and_found_id):
    if request.method == 'POST':
        try:
            item = LostAndFound.objects.filter(lost_and_found_id=lost_and_found_id).first()
            if not item:
                return JsonResponse(tools.ReturnData(code=400, msg='失物招领记录不存在'))
            
            if 'image' not in request.FILES:
                return JsonResponse(tools.ReturnData(code=400, msg='请上传图片'))
            
            image = LostAndFoundImage.objects.create(
                lost_and_found=item,
                image=request.FILES['image']
            )
            
            image_dict = model_to_dict(image)
            image_dict['create_time'] = image.create_time.strftime('%Y-%m-%d %H:%M:%S')
            image_dict['update_time'] = image.update_time.strftime('%Y-%m-%d %H:%M:%S') 
            image_dict['image'] = image.image.url if image.image else None
            
            return JsonResponse(tools.ReturnData(code=200, msg='上传失物招领图片成功', data=image_dict))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'上传失物招领图片失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用POST方法'))

# 删除失物招领图片
@csrf_exempt
def delete_lost_and_found_image(request, image_id):
    if request.method == 'DELETE':
        try:
            image = LostAndFoundImage.objects.filter(id=image_id).first()
            if not image:
                return JsonResponse(tools.ReturnData(code=400, msg='失物招领图片不存在'))
            
            # 删除图片文件
            if image.image:
                if os.path.isfile(image.image.path):
                    os.remove(image.image.path)
            
            # 删除数据库记录
            image.delete()
            return JsonResponse(tools.ReturnData(code=200, msg='删除失物招领图片成功'))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'删除失物招领图片失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用DELETE方法'))
